

<!DOCTYPE html>
<html lang="en" color-mode=light>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>字节码增强（一） - Alex</title>
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="google" content="notranslate" />
  
  <meta name="description" content="​    所谓的字节码增强，即通过程序对.class文...">
  <meta name="author" content="Alex">
  <link rel="icon" href="/images/icons/favicon-16x16.png" type="image/png" sizes="16x16">
  <link rel="icon" href="/images/icons/favicon-32x32.png" type="image/png" sizes="32x32">
  <link rel="apple-touch-icon" href="/images/icons/apple-touch-icon.png" sizes="180x180">
  <meta rel="mask-icon" href="/images/icons/stun-logo.svg" color="#333333">
  
    <meta rel="msapplication-TileImage" content="/images/icons/favicon-144x144.png">
    <meta rel="msapplication-TileColor" content="#000000">
  

  
<link rel="stylesheet" href="/css/style.css">


  
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1445822_s6x2xcokxrl.css">

  

  
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css">

  

  
    
      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/xcode.min.css" name="highlight-style" mode="light">

      
        
        
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.18.1/styles/solarized-dark.min.css" name="highlight-style" mode="dark">

      
  

  <script>
    var CONFIG = window.CONFIG || {};
    var ZHAOO = window.ZHAOO || {};
    CONFIG = {
      isHome: false,
      fancybox: true,
      pjax: false,
      lazyload: {
        enable: true,
        only_post: 'false',
        loading: '/images/theme/loading.gif'
      },
      donate: {
        enable: true,
        alipay: 'https://pic.izhaoo.com/alipay.jpg',
        wechat: 'https://pic.izhaoo.com/wechat.jpg'
      },
      galleries: {
        enable: true
      },
      fab: {
        enable: true,
        always_show: false
      },
      carrier: {
        enable: true
      },
      daovoice: {
        enable: false
      },
      preview: {
        background: {
          default: '/images/theme/welcome-image.jpg',
          api: ''
        },
        motto: {
          default: '我在开了灯的床头下，想问问自己的心啊。',
          api: 'https://v2.jinrishici.com/one.json',
          data_contents: '["data","content"]'
        },
      },
      qrcode: {
        enable: true,
        type: 'url',
        image: 'https://pic.izhaoo.com/weapp-code.jpg',
      },
      toc: {
        enable: true
      },
      scrollbar: {
        model: 'simple'
      },
      notification: {
        enable: false,
        delay: 4500,
        list: '',
        page_white_list: '',
        page_black_list: ''
      }
    }
  </script>

  

  

<meta name="generator" content="Hexo 5.1.1"></head>

<body class="lock-screen">
  <div class="loading"></div>
  


  <nav class="navbar">
    <div class="left">
      
        <i class="iconfont iconqrcode j-navbar-qrcode"></i>
      
      
        <i class="iconfont iconmoono" id="color-toggle" color-toggle="light"></i>
      
    </div>
    <div class="center">字节码增强（一）</div>
    <div class="right">
      <i class="iconfont iconmenu j-navbar-menu"></i>
    </div>
    
      <div id="qrcode-navbar"></div>
    
  </nav>

  

<nav class="menu">
  <div class="menu-wrap">
    <div class="menu-close">
      <i class="iconfont iconbaseline-close-px"></i>
    </div>
    <ul class="menu-content"><li class="menu-item">
        <a href="/ " class="underline "> 首页</a>
      </li><li class="menu-item">
        <a href="/galleries/ " class="underline "> 摄影</a>
      </li><li class="menu-item">
        <a href="/archives/ " class="underline "> 归档</a>
      </li><li class="menu-item">
        <a href="/tags/ " class="underline "> 标签</a>
      </li><li class="menu-item">
        <a href="/categories/ " class="underline "> 分类</a>
      </li><li class="menu-item">
        <a href="/about/ " class="underline "> 关于</a>
      </li></ul>
    
      <div class="menu-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p></div>
    
  </div>
</nav>
  <main id="main">
  <div class="article-wrap">
    <div class="row container">
      <div class="col-xl-3"></div>
      <div class="col-xl-6"><article class="article">
  <div class="wrap">
    <section class="head">
  <img   class="lazyload" data-original="/images/theme/post-image.jpg" src=""  draggable="false">
  <div class="head-mask">
    <h1 class="head-title">字节码增强（一）</h1>
    <div class="head-info">
      <span class="post-info-item"><i class="iconfont iconcalendar"></i>September 24, 2020</span>
      
      <span class="post-info-item"><i class="iconfont iconfont-size"></i>5996</span>
    </div>
  </div>
</section>
    <section class="main">
      <section class="content">
        <blockquote>
<p><strong>增强目标：</strong>在每次使用<code>new</code>关键字创建实例后，调用提前写好的native函数，将实例的引用<code>o</code>、变量名<code>objName</code>、<code>new</code>的java代码行数<code>lineNumber</code>作为参数传入。</p>
<p>这个navtive函数长这个样子:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NativeC</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">native</span> <span class="hljs-keyword">void</span> <span class="hljs-title">newObj</span><span class="hljs-params">(Object o ,<span class="hljs-keyword">int</span> lineNumber,String objName)</span></span>;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">native</span> <span class="hljs-keyword">void</span> <span class="hljs-title">newArr</span><span class="hljs-params">(Object o ,<span class="hljs-keyword">int</span> lineNumber,String objName)</span></span>;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><strong>需要处理的问题：</strong></p>
<ol>
<li>找到<code>new</code>关键字的位置及其在java代码中的行数</li>
<li>找到变量名</li>
<li>插入函数调用，调用native函数。</li>
</ol>
</blockquote>
<h3 id="基于栈的指令-字节码指令"><a href="#基于栈的指令-字节码指令" class="headerlink" title="基于栈的指令-字节码指令"></a>基于栈的指令-字节码指令</h3><p>​    在广大的语言世界中，有两种指令集。一种是像汇编一样的<strong>基于寄存器</strong>的指令，另一种是像字节码这样的<strong>基于栈</strong>的指令。</p>
<p>​    在字节码指令集中，有的指令后需要<strong>操作数</strong>（有的操作数是一个字节，有的是两个字节甚至更多），而有的不需要。几乎所有的字节码指令都会对操作栈产生影响：或是将一些数据压入栈中，或是将数据弹出，或是弹出一些数进行操作后再将新结果压入栈中。<del>这不废话嘛</del></p>
<blockquote>
<p><strong>什么是操作数栈?</strong></p>
<p><strong>操作数栈</strong>是一种栈，栈中存储着一些数据，即<strong>操作数</strong>。它是<strong>栈帧</strong>中的一个数据结构。起到了和汇编中寄存器一样的作用。</p>
</blockquote>
<p>​    个人感觉，基于栈的指令还是很好懂的。（不过在找到官方的<a target="_blank" rel="noopener" href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html">字节码指令文档</a>之前还是很迷糊，文档中给出了每条指令对操作栈的影响）</p>
<p>​    以下是一些字节码指令的例子。</p>
<ul>
<li><p>字节码指令</p>
<ul>
<li><p>iconst_1</p>
<p>当调用字节码指令<code>iconst_1</code> 时，会将常量1压栈</p>
</li>
<li><p>iadd</p>
<p>当调用字节码指令<code>iadd</code>时，会将栈顶两个数据弹栈，如果都是int型变量则会进行加法运算，最后将运算结果压入栈中。</p>
<blockquote>
<p>详细的介绍可以看《深入理解Java虚拟机》8.5.3基于栈的解释器执行过程。</p>
</blockquote>
</li>
</ul>
</li>
<li><p>调用函数的字节码指令</p>
<p><code>invokedynamic</code> <code>invokeinterface</code> <code>invokespecial</code> <code>invokestatic</code> <code>invokevirtual</code></p>
<p>其中<code>invokespecial</code>是调用构造函数的指令 （也可以调用一些其他的特殊函数 ）<code>invokestatic</code>指令则可以调用静态函数。</p>
<p>这两个函数后都要跟两字节的操作数，用来表示被调用函数在常量池中的索引。同时，如果想要成功调用函数，需要保证操作栈栈顶有调用函数所需的参数。</p>
<ul>
<li><p><code>invokespecial</code></p>
<p>​    调用函数前要依次将，调用该函数的对象的引用、所有的函数参数（从左到右）压栈。</p>
<p>​    实例在new之后并不会初始化，只是分配了一块空间，还需要调用&lt;init&gt;函数（即构造函数），该函数由<code>invokespecial</code>指令调用</p>
</li>
<li><p><code>invokestatic</code></p>
<p>​    调用函数前要依次将，从左到右所有的函数参数压栈。</p>
</li>
</ul>
</li>
<li><p>其他的一些会用到的指令</p>
<ul>
<li><p><code>dup</code></p>
<p>​    将一个和操作栈栈顶相同的数据压栈。</p>
</li>
<li><p><code>new</code>与<code>newarray</code>与<code>anewarray</code>与<code>multianewarray</code></p>
<p>​    new指令会将新生成的对象引用压栈。</p>
<p>​    newarray指令会将长度出栈，数组引用压栈。创建基本类型数组时调用。</p>
<p>​    anewarray创建引用类型数组时调用。</p>
<p>​    multianewarray创建多维数组时调用。</p>
</li>
<li><p><code>astore</code>与<code>aload</code></p>
<p>​    这两条指令会影响操作栈和本地变量表。非匿名对象都会存在本地变量表中。</p>
<p>​    <code>astore</code>后跟一个大于3的单字节操作数，执行后将弹出栈顶数据，存入指定位置的本地变量表。</p>
<p>小于等于3的使用<code>astore_0</code>，<code>astore_1</code> ，<code>astore_2</code>，<code>astore_3</code>。</p>
<p>​    <code>aload</code>后跟一个大于3的单字节操作数，执行后将指定位置的本地变量表存入栈顶。</p>
<p>小于等于3的使用<code>aload_0</code>，<code>aload_1</code> ，<code>aload_2</code>，<code>aload_3</code></p>
</li>
</ul>
</li>
<li><p>一些字节码和java代码对应的例子。</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> <span class="hljs-number">8</span> aload_1<br> <span class="hljs-number">9</span> bipush <span class="hljs-number">10</span><br>11 putfield #2 &lt;T.a&gt;<br><span class="hljs-number">14</span> <span class="hljs-keyword">return</span><br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        t.a = <span class="hljs-number">10</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> <span class="hljs-number">8</span> aload_1<br> <span class="hljs-number">9</span> bipush <span class="hljs-number">10</span><br>11 putfield #2 &lt;T.a&gt;<br>14 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br><span class="hljs-number">17</span> aload_1<br>18 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">21</span> <span class="hljs-keyword">return</span><br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        t.a = <span class="hljs-number">10</span>;<br>        NativeC._new(Thread.currentThread(), t);<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> <span class="hljs-number">8</span> aload_1<br> <span class="hljs-number">9</span> bipush <span class="hljs-number">10</span><br>11 putfield #2 &lt;T.a&gt;<br>14 new #3 &lt;T&gt;<br><span class="hljs-number">17</span> dup<br>18 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br><span class="hljs-number">21</span> astore_2<br><span class="hljs-number">22</span> aload_2<br><span class="hljs-number">23</span> bipush <span class="hljs-number">100</span><br>25 putfield #2 &lt;T.a&gt;<br><span class="hljs-number">28</span> <span class="hljs-keyword">return</span><br>     <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        t.a = <span class="hljs-number">10</span>;<br>        T t2 = <span class="hljs-keyword">new</span> T();<br>        t2.a = <span class="hljs-number">100</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> <span class="hljs-number">8</span> aload_1<br> <span class="hljs-number">9</span> bipush <span class="hljs-number">10</span><br>11 putfield #2 &lt;T.a&gt;<br>14 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br><span class="hljs-number">17</span> aload_1<br>18 invokestatic #6 &lt;NativeC._new&gt;<br>21 new #3 &lt;T&gt;<br><span class="hljs-number">24</span> dup<br>25 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br><span class="hljs-number">28</span> astore_2<br><span class="hljs-number">29</span> aload_2<br><span class="hljs-number">30</span> bipush <span class="hljs-number">100</span><br>32 putfield #2 &lt;T.a&gt;<br>35 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br><span class="hljs-number">38</span> aload_2<br>39 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">42</span> <span class="hljs-keyword">return</span><br>    <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        t.a = <span class="hljs-number">10</span>;<br>        NativeC._new(Thread.currentThread(), t);<br><br>        T t2 = <span class="hljs-keyword">new</span> T();<br>        t2.a = <span class="hljs-number">100</span>;<br>        NativeC._new(Thread.currentThread(), t2);<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java">0 new #3 &lt;T&gt;<br><span class="hljs-number">3</span> dup<br>4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br><span class="hljs-number">7</span> astore_1<br><span class="hljs-number">8</span> <span class="hljs-keyword">return</span><br>    <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>&#125;<br></code></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> 8 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br><span class="hljs-number">11</span> aload_1<br>12 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">15</span> <span class="hljs-keyword">return</span><br>     <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        NativeC._new(Thread.currentThread(), t);<br>&#125;<br><br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java">0 new #3 &lt;T&gt;<br><span class="hljs-number">3</span> dup<br>4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br><span class="hljs-number">7</span> pop<br><span class="hljs-number">8</span> <span class="hljs-keyword">return</span><br>    <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">new</span> T();<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 invokestatic #3 &lt;java/lang/Thread.currentThread&gt;<br> 3 new #4 &lt;T&gt;<br> <span class="hljs-number">6</span> dup<br> 7 invokespecial #5 &lt;T.&lt;init&gt;&gt;<br>10 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">13</span> <span class="hljs-keyword">return</span><br>     <br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        NativeC._new(Thread.currentThread(), <span class="hljs-keyword">new</span> T());<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> <span class="hljs-number">7</span> astore_1<br> <span class="hljs-number">8</span> aload_1<br> 9 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br>12 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">15</span> <span class="hljs-keyword">return</span><br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        T t = <span class="hljs-keyword">new</span> T();<br>        NativeC._new(t,Thread.currentThread());<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"> 0 new #3 &lt;T&gt;<br> <span class="hljs-number">3</span> dup<br> 4 invokespecial #4 &lt;T.&lt;init&gt;&gt;<br> 7 invokestatic #5 &lt;java/lang/Thread.currentThread&gt;<br>10 invokestatic #6 &lt;NativeC._new&gt;<br><span class="hljs-number">13</span> <span class="hljs-keyword">return</span><br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fun1</span><span class="hljs-params">()</span> </span>&#123;<br>        NativeC._new(<span class="hljs-keyword">new</span> T(),Thread.currentThread());<br>&#125;<br></code></pre></td></tr></table></figure>



<h3 id="Class文件的结构"><a href="#Class文件的结构" class="headerlink" title="Class文件的结构"></a>Class文件的结构</h3><p>​    .class文件是将java文件编译后生成的，其中包含了类的各种信息。详细内容可见《深入理解JAVA虚拟机》第六章内容。</p>
<p>​    根据本次增强目标，我们需要在每一个实例创建后，调用提前写好的static native方法   <code>newObj</code>（该方法作为NativeC.java的静态函数，调用时需要在常量池中可以找到），并将该实例作为函数参数传入，只需要了解Class文件中<strong>方法表 、常量池</strong>的部分即可。</p>
<ul>
<li><p>关于方法表的要求</p>
<p>​    <strong>方法表项</strong>是个复杂的结构，其包含如访问标记、描述符、<strong>属性表</strong>集合等信息，而我们的字节码就存储在<strong>属性表</strong>中。属性表中提供给方法表使用的属性有很多，其中我们需要使用到的为Code。</p>
<ul>
<li><p>code属性</p>
<p>​    code属性中有很多信息，其中我们涉及到的有：max_stack（方法中允许使用的<strong>操作栈</strong>层数），LocalVariableTable（方法中的局部变量表），以及最重要的code（字节码）。</p>
</li>
</ul>
<ul>
<li><p>要求</p>
<ol>
<li>因为需要自己插入新的代码，会影响操作栈层数，必须保证max_stack够</li>
<li>需要找到新实例生成的代码，并用到该实例，调用native方法，需要清楚字节码指令的执行方式。</li>
</ol>
</li>
<li><p>关于常量池的要求（其实在后续代码中也没有用到常量池，javassist工具偷偷的修改了文件的常量池）</p>
<p>​    假设待增强文件为A.class，如果想要能够在A的代码中调用其他类的函数，需要将这个<strong>函数的字符引用</strong>加入到常量池中（即CONSTANT_Methodref_info），而因为该常量需要存有两个引用，一是指向<strong>声明该函数的类的描述符</strong>（即CONSTANT_Class_info），二是<strong>指向名称及类型描述符</strong>（即CONSTANT_NameAndType），所以理论上如果<strong>要能调用该native函数需要添加这三项到常量池</strong>。</p>
<blockquote>
<p>下图为<strong>函数的字符引用</strong>信息，通过jclasslib工具得到，右侧上下分别为<strong>声明该函数的类的描述符</strong>和<strong>指向名称及类型描述符</strong>。#64,#65代表他们在常量池中的索引位</p>
</blockquote>
<p><a href="constant_info1.png"><img   class="lazyload" data-original="/2020/09/24/javassist/constant_info1.png" src="" ><span class="image-caption">constant_info1</span></a></p>
</li>
</ul>
</li>
</ul>
<h3 id="插桩方案"><a href="#插桩方案" class="headerlink" title="插桩方案"></a>插桩方案</h3><ul>
<li><p>使用javassist工具，遍历方法中的字节码，找到创建实例的指令。</p>
</li>
<li><p>调整操作栈顶的数据，使得可以调用native函数</p>
</li>
<li><p>插入字节码指令。</p>
</li>
</ul>
      </section>
      <section class="extra">
        
          <ul class="copyright">
  
    <li><strong>本文作者：</strong>Alex</li>
    <li><strong>本文链接：</strong><a href="https://alexande.gitee.io/2020/09/24/javassist/index.html" title="https:&#x2F;&#x2F;alexande.gitee.io&#x2F;2020&#x2F;09&#x2F;24&#x2F;javassist&#x2F;index.html">https:&#x2F;&#x2F;alexande.gitee.io&#x2F;2020&#x2F;09&#x2F;24&#x2F;javassist&#x2F;index.html</a></li>
    <li><strong>版权声明：</strong>本博客所有文章均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" title="BY-NC-SA" target="_blank" rel="noopener">BY-NC-SA</a> 许可协议，转载请注明出处！</li>
  
</ul>
        
        
          <section class="donate">
  <div id="qrcode-donate">
    <img   class="lazyload" data-original="https://pic.izhaoo.com/alipay.jpg" src="" >
  </div>
  <div class="icon">
    <a href="javascript:;" id="alipay"><i class="iconfont iconalipay"></i></a>
    <a href="javascript:;" id="wechat"><i class="iconfont iconwechat-fill"></i></a>
  </div>
</section>
        
        
  <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/instrument/" rel="tag">instrument</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/java/" rel="tag">java</a></li></ul> 

        
  <nav class="nav">
    <a href="/2020/09/26/javassist2/"><i class="iconfont iconleft"></i>字节码增强（二）</a>
    <a></a>
  </nav>

      </section>
      
    </section>
  </div>
</article></div>
      <div class="col-xl-3">
        
          
  <aside class="toc-wrap">
    <h3 class="toc-title">文章目录：</h3>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9F%BA%E4%BA%8E%E6%A0%88%E7%9A%84%E6%8C%87%E4%BB%A4-%E5%AD%97%E8%8A%82%E7%A0%81%E6%8C%87%E4%BB%A4"><span class="toc-text">基于栈的指令-字节码指令</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Class%E6%96%87%E4%BB%B6%E7%9A%84%E7%BB%93%E6%9E%84"><span class="toc-text">Class文件的结构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%8F%92%E6%A1%A9%E6%96%B9%E6%A1%88"><span class="toc-text">插桩方案</span></a></li></ol>
  </aside>

        
      </div>
    </div>
  </div>
</main>
  

<footer class="footer">
  <div class="footer-social"><a 
        href="tencent://message/?Menu=yes&uin=272991962 "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconQQ "></i>
      </a><a 
        href="https://github.com/zheng-kai "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  icongithub-fill "></i>
      </a><a 
        href="https://gitee.com/AlexAnde "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color= '#9f7be1'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  gitee-fill-round "></i>
      </a><a 
        href="mailto:272991962@qq.com "
        target="_blank"
        class="footer-social-item"
        onMouseOver="this.style.color=  '#12B7F5'" 
        onMouseOut="this.style.color='#33333D'">
          <i class="iconfont  iconmail "></i>
      </a></div>
  
    <div class="footer-copyright"><p>Powered by <a target="_blank" href="https://hexo.io">Hexo</a>  |  Theme - <a target="_blank" href="https://github.com/izhaoo/hexo-theme-zhaoo">zhaoo</a></p></div>
  
</footer>
  
      <div class="fab fab-plus">
    <i class="iconfont iconplus"></i>
  </div>
  
  
  <div class="fab fab-up">
    <i class="iconfont iconcaret-up"></i>
  </div>
  
  
    <div class="scrollbar j-scrollbar">
  <div class="scrollbar-current j-scrollbar-current"></div>
</div>
  
  
    
<script src="/js/color-mode.js"></script>

  
</body>

<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>



  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>




  
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>






  
<script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>




<script src="/js/utils.js"></script>
<script src="/js/script.js"></script>





  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      } else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>













</html>